<template>
  <el-card style="width: 100%">
    <!-- 顶部 -->
    <template #header>
      <div class="flex-between">
        <span>用户信息管理</span>
        <el-button type="primary" @click="openDialog">新增</el-button>
      </div>
    </template>

    <!-- 查询 -->
    <el-form :inline="true" :model="query" class="mb-3">
      <el-form-item label="关键字">
        <el-input v-model="query.keyword" placeholder="用户名 / 昵称" clearable />
      </el-form-item>
      <el-button type="primary" @click="onQuery">查询</el-button>
      <el-button @click="onReset">重置</el-button>
    </el-form>

    <!-- 列表 -->
    <el-table :data="list" border stripe style="width: 100%" class="nowrap-table">
      <el-table-column prop="userName" label="用户名" min-width="140" />
      <el-table-column prop="realName" label="昵称" min-width="140" />
      <el-table-column prop="useType" label="用户类别" min-width="100" />
      <el-table-column label="职称" min-width="120">
        <template #default="{ row }">
          {{ titleMap[row.docTitleID] || row.docTitleID }}
        </template>
      </el-table-column>
      <el-table-column label="科室" min-width="120">
        <template #default="{ row }">
          {{ deptMap[row.deptID] || row.deptID }}
        </template>
      </el-table-column>
      <el-table-column label="挂号级别" min-width="120">
        <template #default="{ row }">
          {{ levelMap[row.registLeID] || row.registLeID }}
        </template>
      </el-table-column>
      <el-table-column prop="isScheduling" label="是否排班" min-width="100" />
      <el-table-column label="操作" fixed="right" min-width="180">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="onEdit(row.id)">编辑</el-button>
          <el-button size="small" type="danger" @click="onDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="mt-4 text-right">
      <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          v-model:current-page="query.page"
          v-model:page-size="query.pageSize"
          @current-change="onPageChange"
          @size-change="onSizeChange"
      />
    </div>

    <!-- 新增 / 编辑 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="640px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="90px" status-icon>
        <el-row :gutter="20">
          <!-- 新增：用户类别 -->
          <el-col :span="12">
            <el-form-item label="用户类别" prop="useType">
              <el-input-number v-model="form.useType" :min="1" style="width:100%" />
            </el-form-item>
          </el-col>

          <!-- 原有字段 -->
          <el-col :span="12">
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="form.userName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="昵称" prop="realName">
              <el-input v-model="form.realName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职称" prop="docTitleID">
              <el-select v-model="form.docTitleID" placeholder="请选择职称">
                <el-option v-for="t in titleOptions" :key="t.id" :label="t.name" :value="t.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="科室" prop="deptID">
              <el-select v-model="form.deptID" placeholder="请选择科室">
                <el-option v-for="d in deptOptions" :key="d.id" :label="d.name" :value="d.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="挂号级别" prop="registLeID">
              <el-select v-model="form.registLeID" placeholder="请选择级别">
                <el-option v-for="l in levelOptions" :key="l.id" :label="l.name" :value="l.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否排班" prop="isScheduling">
              <el-select v-model="form.isScheduling" placeholder="请选择">
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" type="password" show-password />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

interface UserItem {
  id?: number
  userName: string
  password?: string
  realName: string
  useType: number | ''
  docTitleID: number | ''
  deptID: number | ''
  isScheduling: string
  registLeID: number | ''
}

const list  = ref<UserItem[]>([])
const total = ref(0)
const query = reactive({ keyword: '', page: 1, pageSize: 10 })

const titleOptions = ref<{id:number,name:string}[]>([])
const deptOptions  = ref<{id:number,name:string}[]>([])
const levelOptions = ref<{id:number,name:string}[]>([])
const titleMap: Record<number,string> = {}
const deptMap:  Record<number,string> = {}
const levelMap:Record<number,string> = {}

function arr(r:any) {
  return Array.isArray(r) ? r
      : Array.isArray(r.records) ? r.records
          : Array.isArray(r.data)    ? r.data
              : []
}

async function loadDictionaries() {
  const [cRes, lRes, dRes] = await Promise.all([
    axios.get('/api/master/constant/item/list'),
    axios.get('/api/master/reglevel', { params:{keyword:''} }),
    axios.get('/api/master/dept',    { params:{page:1,pageSize:500,keyword:''} })
  ])
  titleOptions.value = arr(cRes.data)
      .filter((c:any)=>c.constanttypeid===8)
      .map((c:any)=>({id:c.id,name:c.constantname}))
  titleOptions.value.forEach(i=>titleMap[i.id]=i.name)
  levelOptions.value = arr(lRes.data).map((l:any)=>({id:l.id,name:l.registname}))
  levelOptions.value.forEach(i=>levelMap[i.id]=i.name)
  deptOptions.value = arr(dRes.data).map((d:any)=>({id:d.id,name:d.deptname}))
  deptOptions.value.forEach(i=>deptMap[i.id]=i.name)
}

async function loadData() {
  const { data } = await axios.get('/api/master/user/list')
  let rows = arr(data) as UserItem[]
  if(query.keyword) {
    rows = rows.filter(u=>u.userName.includes(query.keyword)||u.realName.includes(query.keyword))
  }
  total.value = rows.length
  const start = (query.page-1)*query.pageSize
  list.value = rows.slice(start,start+query.pageSize)
}

function onQuery()      { query.page=1; loadData() }
function onReset()      { query.keyword=''; onQuery() }
function onPageChange(p:number) { query.page=p; loadData() }
function onSizeChange(s:number) { query.pageSize=s; query.page=1; loadData() }

const dialogVisible = ref(false)
const dialogTitle   = ref('')
const formRef       = ref()

const form = reactive<UserItem>({
  userName:'', realName:'', useType:'', docTitleID:'', deptID:'', registLeID:'', isScheduling:'否', password:''
})

const rules = {
  userName:     [{ required:true,message:'请输入用户名',trigger:'blur'}],
  realName:     [{ required:true,message:'请输入昵称',trigger:'blur'}],
  useType:      [{ required:true,message:'请选择用户类别',trigger:'change'}],
  docTitleID:   [{ required:true,message:'请选择职称',trigger:'change'}],
  deptID:       [{ required:true,message:'请选择科室',trigger:'change'}],
  registLeID:   [{ required:true,message:'请选择级别',trigger:'change'}],
  isScheduling: [{ required:true,message:'请选择是否排班',trigger:'change'}],
  password:     [{ validator:(_r,v,cb)=>{ if(!form.id&&!v) cb(new Error('请输入密码')); else cb() }, trigger:'blur'}]
}

function openDialog() {
  dialogTitle.value='新增用户'
  Object.assign(form, { id:undefined, userName:'', realName:'', useType:'', docTitleID:'', deptID:'', registLeID:'', isScheduling:'否', password:'' })
  dialogVisible.value=true
}

async function onEdit(id?:number) {
  if(!id) return
  const { data } = await axios.get(`/api/master/user/getById/${id}`)
  Object.assign(form, data, { password:'' })
  dialogTitle.value='编辑用户'
  dialogVisible.value=true
}

async function onSubmit() {
  await formRef.value?.validate()
  const payload = { ...form }
  if(!payload.password) delete payload.password
  if(form.id) {
    await axios.put('/api/master/user/update', payload)
    ElMessage.success('修改成功')
  } else {
    await axios.post('/api/master/user/save', payload)
    ElMessage.success('新增成功')
  }
  dialogVisible.value=false
  loadData()
}

function onDelete(id?:number) {
  if(!id) return
  ElMessageBox.confirm('确定删除该用户吗?','提示',{type:'warning'})
      .then(async()=>{
        await axios.delete(`/api/master/user/deleteById/${id}`)
        ElMessage.success('删除成功')
        loadData()
      })
      .catch(()=>{})
}

onMounted(async()=>{
  await loadDictionaries()
  await loadData()
})
</script>

<style scoped>
.flex-between      { display:flex; justify-content:space-between; align-items:center }
.mb-3              { margin-bottom:12px }
.nowrap-table .cell{ white-space:nowrap }
</style>
